<template>
  <div>
    <Drawer
      ref="modal"
      :title="`${editType === 'create' ?  $t('permissionsIndex.UserAdd') : $t('permissionsIndex.UserEdit')}`"
      :width="600"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
    >
      <Form
        ref="form"
        :labelWidth="100"
        :model="formData"
        :rules="formRule"
      >
       
        <FormItem prop="username" :label="$t('permissionsIndex.UserName')">
          <Input v-if="editType === 'create'" v-model.trim="formData.username" :placeholder="$t('permissionsIndex.UserInputName')" />
          <div v-else>{{formData.username}}</div>
        </FormItem>
        <FormItem prop="realName" :label="$t('permissionsIndex.UserRealName')">
          <Input v-model.trim="formData.realName" :placeholder="$t('permissionsIndex.UserInputRealName')" />
        </FormItem>
        <!-- <FormItem prop="age" :label="$t('permissionsIndex.UserOld')">
          <Input type="number" v-model="formData.age" :placeholder="$t('permissionsIndex.UserInputOld')" />
        </FormItem> -->
        <FormItem prop="age" :label="$t('permissionsIndex.UserOld')">
          <InputNumber
            v-model="formData.age"
            :min="1" :max="200"
            :step="1"
            :style="{ width: '100px' }"
          />
        </FormItem>
        <FormItem v-if ="editType=='create'" prop="password" :label="$t('loginIndex.loginPassword')">
          <Input type="password" v-model="formData.password" :placeholder="$t('permissionsIndex.UserInputPass')" />
        </FormItem>
        <FormItem v-if ="editType=='create'" prop="passwordSure" :label="$t('loginIndex.loginpwdCheck')">
          <Input type="password" v-model="formData.passwordSure" :placeholder="$t('permissionsIndex.UserInputSelPass')" />
        </FormItem>
        <FormItem prop="mail"  :label="$t('permissionsIndex.UserEmail')">
          <Input v-model="formData.email" :placeholder="$t('permissionsIndex.UserInputEmail')"/>
        </FormItem>
        <!-- <FormItem prop="recordTypes" :label="$t('BodyTemperatureIndex.BodyTemAnimalDepartment')">
          <Cascader :data="recordTypes" v-model="recordType"
          @on-change="handleChange1"
          @on-visible-change="handleChange" change-on-select></Cascader>
        </FormItem> -->
        <FormItem prop="roles" :label="$t('permissionsIndex.UserRoleSel')">
          <CheckboxGroup v-model="roles">
              <Checkbox v-for="(item, idx) in roleCheck" :key="idx" :value="item.id" :label="item.id">{{item.roleName}}</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import _ from 'lodash'
import {
  mapState,
} from 'vuex'

import modalMixin from '@/utils/mixins/modalMixin.js'
import {
  create,
  update,
  detail,
} from '@/api/user.js'
import {
  getList,
} from '@/api/Role.js'

const DEFAULT_FORM = {
  username: '',
  realName: '',
  age: 1,
  password: '',
  passwordSure: '',
  email: '',
}

//自定义规则校验邮箱输 入
var validateEmail = (rule, value, callback) => {
  
};

export default {
  mixins: [
    modalMixin,
  ],

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      recordTypes: [],
      recordType: [],
      departsdata: '',
      roleCheck: [],
      roles: [],
      formData: _.cloneDeep(DEFAULT_FORM),
      formRule: {
        realName:{ required: true, validator: (rule, value, callback) => {
            this.formData.realName = this.formData.realName.replace(/\s*/g,"");
            if (this.formData.realName.length == 0) {
              return callback(new Error(this.$t('permissionsIndex.UserInputRealName')))
            }else {
              return callback()
            }
          } , trigger: 'blur'
        },
        username: { required: true, validator: (rule, value, callback) => {
            this.formData.username = this.formData.username.replace(/\s*/g,"");
            if (this.formData.username.length == 0) {
              return callback(new Error(this.$t('permissionsIndex.UserInputName')))
            }else {
              return callback()
            }
          } , trigger: 'blur'
        },
        age: { required: true, message: this.$t('permissionsIndex.UserInputOld') },
        password: { required: true, validator: (rule, value, callback) => {
            let reg=/^[0-9]{6,12}$/
            if (this.formData.password.length == 0) {
              return callback(new Error(this.$t('permissionsIndex.UserInputPass')))
            } else if(this.formData.password.length<6){
              return callback(new Error(this.$t('loginIndex.loginPhoneMin')))
            }else if(reg.test(this.formData.password)==false){
              return callback(new Error(this.$t('loginIndex.loginpwdCheck9')))
            }
            else {
              return callback()
            }
          } , trigger: 'blur'
        },
        recordTypes: { required: true, validator: (rule, value, callback) => {
      
          if (this.recordType.length == 0) {
            return callback(new Error(this.$t('permissionsIndex.UserDeparSel')))
          } else {
            return callback()
          }

        } },
        // roles: { required: true, validator: (rule, value, callback) => {
        //   if (this.roles.length == 0) {
        //     return callback(new Error(this.$t('permissionsIndex.UserRoleSel')))
        //   } else {
        //     return callback()
        //   }
        // } },
        passwordSure: { required: true, validator: (rule, value, callback) => {
          if (this.formData.passwordSure) {
            if (this.formData.passwordSure != this.formData.password) {
              return callback(new Error(this.$t('permissionsIndex.UserPassDown')))
            } else {
              return callback()
            }
          } else {
            return callback(new Error(this.$t('permissionsIndex.UserpassSure')))
          }
        }, trigger: 'blur' },
        mail: {validator: (rule, value, callback) => {
          var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
          if (this.formData.email) {
            if (!reg.test(this.formData.email)) {
              return callback(new Error(this.$t('permissionsIndex.UserEmailNo')))
            } else {
              return callback()
            }
          } else {
            return callback()
          }
        }, trigger: 'blur' },
      },
    }
  },
  computed: {
    ...mapState([
      'departId',
    ]),
    ifSelFile () {
      return typeof this.formData.file === 'object'
    },
  },

  mounted () {
    this.show = true
    this.getDataList()
    this.getRole()
    
    if (this.editType === 'update') {
      this.getDetail(this.editItem.id)

      console.log('this.editItem')
      console.log(this.editItem)
      this.formData = {
        username: this.editItem.username,
        realName: this.editItem.realName,
        age: this.editItem.age,
        email: this.editItem.email=='null'?'':this.editItem.email,
      }
      if (this.editItem.levelDepartId) {
        setTimeout(()=>{
        this.recordType = this.editItem.levelDepartId.split(',').map(item => { // item为数组的元素
          return Number(item)
        })      
        },500)
      }
          // this.formData.roles = ["4ed483c8045b4d9a8a058305a2286f16"]

      // if (this.editItem.roleList) {
        // this.formData.roles = ["a544b82a3be24369854ee704969c6234"]
      // }

    }else{
      
    }
  },

  methods: {
    async getDataList () {
      // 通过vuex调接口获取公司名depart是vuex中别的一套vuex模块
      const list = await this.$store.dispatch('depart/getList')
      let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
      let listStringLabel = listString.replace(/"departName"/g, '"label"')
      let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
      // let listStringChildren1 = listStringChildren.replace(/"null"/g, "''")
      var aParse = JSON.parse(listStringChildren)
      function dG(params) {
        params.forEach(v=>{
          if(v.children){
            dG(v.children)
          }else{
            v.children=[]
          }
        })
      }
      dG(aParse)
      this.recordTypes = aParse
    },
    handleChange (value) {
      
      
      if (!value) {
        console.log(this.recordType)
        
        // this.departsdata = this.recordType[this.recordType.length - 1]
        // console.log(this.departsdata)
        // this.searcName()
      }
    },
    handleChange1 (value) {
      
      // Change时候赋值给recordType  然后关闭级联下拉框可以选中
      this.recordType = value
      // //console.log('woshi====',this.recordType)
    },
    handleUpload (file) {
      this.formData.file = file
      return false
    },
    generateFormData () {
      if (!this.formData.email||this.editItem.email=='null') {
        this.formData.email=''
      }
      if(this.editType === 'update'){
        if (!this.formData.age||this.editItem.age=='null'||this.formData.age=='null') {
          this.formData.age=''
        }
      }
      const data = _.cloneDeep(this.formData)
      // data.departId = this.recordType[this.recordType.length - 1]
      console.log(this.recordType)
      console.log(this.roles)
      data.levelDepartId = this.recordType
      data.roles = this.roles
      if (this.editType === 'update') {
        data.id = this.editItem.id
      }
      const formData = new FormData()
      const keys = Object.keys(data)
      for (let i = 0; i < keys.length; i += 1) {
        const key = keys[i]
        formData.append(key, data[key])
      }
      console.log(formData)
      return formData
    },

    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'create') {
        this.handleCreate()
      }
      if (ifVlid && this.editType === 'update') {
        this.handleUpdate()
      }
    },
    async getDetail (id) {
      let that = this
      const { success, data } = await detail({ id })
      if (success) {

        // console.log(data.data)
        // this.roleCheck = data.data
        let roleL = data.data[0].roleList
        console.log(roleL)
        let roleArr = []
        if (roleL.length > 0) {
          roleL.forEach((item, index) => {
            roleArr.push(item.roleId)
          })
          // that.formData.roles = ['4ed483c8045b4d9a8a058305a2286f16']
          this.roles = roleArr
        }
      }
    },

    async getRole () {
      let areaId = {
        page: 1,
        limit: 100,
        username: '',
      }
      const { success, data } = await getList(areaId)
      if (success) {
        // console.log(data.data)
        this.roleCheck = data.data
      }
      
    },
    async handleCreate () {
      const formData = this.generateFormData()
      const { success, data } = await create(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        if(data=="权限组已存在"){
          this.$Message.error(this.$t('newDevices.createdSiteTip3'))
        }else if(data=="用户名已存在"){
          this.$Message.error(this.$t('newDevices.createdAdminTip2'))
        }else{
          this.$Message.error(data)
        }
      }
    },
    async handleUpdate () {
      const formData = this.generateFormData()
      const { success, data } = await update(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        if(data=="权限组已存在"){
          this.$Message.error(this.$t('newDevices.createdSiteTip3'))
        }else if(data=="用户名已存在"){
          this.$Message.error(this.$t('newDevices.createdAdminTip2'))
        }else{
          this.$Message.error(data)
        }
      }
    },
  },
}
</script>
